package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.api.helper.UserHelper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.BigDecimalUtils;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.helper.MallMemberHelper;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.MallMember;
import com.rockcent.mall.lib.domain.MallMemberFundFlow;
import com.rockcent.mall.lib.domain.MallMemberRechargeFlow;
import com.rockcent.mall.lib.domain.enumclass.AuditStatus;
import com.rockcent.mall.lib.domain.enumclass.MallMemberRechargeType;
import com.rockcent.mall.lib.domain.enumclass.MallMemberStatus;
import com.rockcent.mall.lib.dto.MallMemberRechargeFlowDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.service.MallMemberRechargeSrv;
import com.rockcent.service.MallMemberSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * 充值管理
 * Created by zhangjh on 2017/3/8.
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MallMemberRechargeController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallMemberRechargeController.class);

    @Autowired
    private MallMemberRechargeSrv mallMemberRechargeSrv;


    @Autowired
    private MallMemberSrv mallMemberSrv;

    @Autowired
    private UserHelper userHelper;

    /**
     * @api {post} /v1/mall/member/recharge/save M 充值提交
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} rechargeAccount <code>必须参数</code> 汇款账号
     * @apiParam {BigDecimal} rechargeAmount <code>必须参数</code> 金额
     * @apiParam {String} rechargeDate <code>必须参数</code> 充值日期
     * @apiParam {String} rechargeVoucher <code>必须参数</code> 充值凭证
     * @apiParam {String} remark <code>必须参数</code> 备注
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code":"1",
     * "desc":"成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_SAVE, method = RequestMethod.POST)
    public JsonResult addInfo(@RequestBody MallMemberRechargeFlow dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = (JsonResult jsonResult) -> {


            if (null == dto) {
                jsonResult.errorParam("汇款信息为空", log);
                return;
            }
            if (dto.getRechargeAccount() == null) {
                jsonResult.errorParam("汇款账号为空格", log);
                return;
            }
            BigDecimal rechargeAmount = dto.getRechargeAmount();
            if (null == rechargeAmount) {
                jsonResult.errorParam("充值金额为空", log);
                return;
            }

            if(rechargeAmount.compareTo( BigDecimal.valueOf(0))<0){
                jsonResult.errorParam("充值金额必须大于0元", log);
                return;
            }

            if(!BigDecimalUtils.isNumber(String.valueOf(rechargeAmount))) {
                jsonResult.errorParam("充值金额最多两位小数", log);
                return;
            }

            if (StringUtils.isBlank(dto.getRechargeDate())) {
                jsonResult.errorParam("汇款日期为空", log);
                return;
            }
//            if (StringUtils.isBlank(dto.getRechargeVoucher())) {
//                jsonResult.errorParam("汇款凭证为空", log);
//                return;
//            }


            MallMember mallMember = mallMemberSrv.findTop1ByMallIdByLastUpdatedDesc(mallId);
            if (null == mallMember) {
                jsonResult.errorParam("非会员不能提交充值", log);
                return;
            }
            MallMemberStatus status  =  mallMember.getStatus();

            if (MallMemberStatus.NOT_MEMBER == status) {
                jsonResult.errorParam("未认证会员不能提交充值", log);
                return;
            }else if (MallMemberStatus.AUDITING == status) {
                jsonResult.errorParam("会员开通审核中,不能充值", log);
                return;
            }else if (MallMemberStatus.PROBATION_MEMBER == status || MallMemberStatus.AUDIT_REFUSE == status) {//
                if (rechargeAmount.compareTo(BigDecimal.valueOf(10000)) < 0) {
                    jsonResult.errorParam("首次充值金额必须大于10000元", log);
                    return;
                }
                mallMember.setStatus(MallMemberStatus.AUDITING);
                mallMemberSrv.save(mallMember);
            }


            String seqNo = MallMemberHelper.SINGLETON.createRechargeSeqNo(MallMemberRechargeType.OUTLINE_RECHARGE);
            dto.setAuditStatus(AuditStatus.WAIT);
            dto.setSeqNo(seqNo);
            dto.setMallId(mallId);
            dto.setMallMemberId(mallMember.getId());
//
            mallMemberRechargeSrv.save(dto);

        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /v1/mall/member/recharge/page R 充值记录分页
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} auditStatus <code>必选参数</code> 状态 ：ALL("全部"),WAIT("待审核"),AUDITED("已审核"), PASS("审核通过"),REFUSE("不通过")
     * @apiParam {String} mallName <code>可选参数</code> 平台名称
     * @apiParam {String} mallId <code>可选参数</code> 平台商ID
     * @apiParam {String} rechargeAccount <code>可选参数</code> 汇款帐号
     * @apiParam {String} rechargeAmount <code>可选参数</code> 充值金额
     * @apiParam {String} rechargeDate <code>可选参数</code> 汇款时间
     * @apiParam {String} beginDate <code>可选参数</code> 提交开始时间
     * @apiParam {String} endDate <code>可选参数</code> 提交结束时间
     *
     * @apiSuccess {long} id ID
     * @apiSuccess {String} lastUpdated 操作时间
     * @apiSuccess {String} seqNo 流水号
     * @apiSuccess {long} mallId 平台id
     * @apiSuccess {long} mallMemberId 会员id
     * @apiSuccess {BigDecimal} rechargeAmount 汇款金额
     * @apiSuccess {String} rechargeAccount 汇款账号
     * @apiSuccess {String} rechargeDate 汇款日期
     * @apiSuccess {String} rechargeVoucher 凭证
     * @apiSuccess {String} auditStatus 审核状态
     *
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "data": [
     *       {
     *         "id": 2,
     *         "dateCreated": "2017-03-10 11:46:54",
     *         "lastUpdated": "2017-03-10 11:46:54",
     *         "seqNo": "001489117673114",
     *         "mallId": 51,
     *         "mallMemberId": 1,
     *         "rechargeAmount": 10000,
     *         "rechargeAccount": "6228480402564890018",
     *         "rechargeDate": "2016-03-10",
     *         "rechargeVoucher": "http://wx.qlogo.cn/mmopen/UOCHvzUGAIV8FXCZV5LEuCyEFNLvYqlw6aicxXiasYKr6qmesZKTiatyujJO42jdfW877UJsmeVj0HwsJRibGIxWSvlAFSiaicAD5V/0",
     *         "auditStatus": "WAIT"
     *       }
     *     ],
     *     "totalCount": 1,
     *     "totalPage": 1,
     *     "pageNo": 0,
     *     "pageSize": 10,
     *     "url": "/mall/member/recharge/page",
     *     "prevUrl": "/mall/member/recharge/page?pageNo=0&pageSize=10",
     *     "nextUrl": "/mall/member/recharge/page?pageNo=0&pageSize=10"
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_PAGE, method = RequestMethod.GET)
    public JsonResult page(MallMemberRechargeFlowDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();

        RestDoing doing = jsonResult -> {
            if (null == dto) {
                jsonResult.errorParam("查询条件为空", log);
                return;
            }
            if (!EnumUtils.isValidEnum(AuditStatus.class, dto.getAuditStatus())) {
                jsonResult.errorParam("审核状态为空", log);
                return;
            }

            if (null == dto.getMallId()) {
                dto.setMallId(mallId);
            }


            PageResult<MallMemberRechargeFlowDto> pageResult = mallMemberRechargeSrv.findMallMemberRechargePage(dto, getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_MEMBER_RECHARGE_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {post} /v1/mall/member/recharge/batch/save R 批量充值
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {BigDecimal} rechargeAmount <code>必须参数</code> 金额
     * @apiParam {String} transactionType <code>必须参数</code> 充值类型：RECHARGE_PRESENTED("充值赠送")，RECHARGE_COMMON("普通充值")
     * @apiParam {String} mallIds <code>必须参数</code> 平台id集合
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code":"1",
     * "desc":"成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_BATCH_SAVE, method = RequestMethod.POST)
    public JsonResult rechargeBatch(@RequestBody MallMemberRechargeFlowDto dto, HttpServletRequest request) {
        RestDoing doing = (JsonResult jsonResult) -> {

            List<Long> mallIds = dto.getMallIds();
            if (null == mallIds || mallIds.isEmpty()) {
                jsonResult.errorParam("请选择需要充值的平台", log);
                return;
            }
            String transactionType = dto.getTransactionType();
            if (StringUtils.isBlank(transactionType)) {
                jsonResult.errorParam("充值类型为空", log);
                return;
            }
            BigDecimal rechargeAmount = dto.getRechargeAmount();
            if (null == rechargeAmount) {
                jsonResult.errorParam("充值金额为空", log);
                return;
            }

            if(rechargeAmount.compareTo(BigDecimal.valueOf(0))<0){
                jsonResult.errorParam("充值金额必须大于0元", log);
                return;
            }

            if(!BigDecimalUtils.isNumber(String.valueOf(rechargeAmount))) {
                jsonResult.errorParam("充值金额最多两位小数", log);
                return;
            }


            for(Long mallId:mallIds){
                MallMember mallMember = mallMemberSrv.findTop1ByMallIdByLastUpdatedDesc(mallId);

                if (null == mallMember) {
                    jsonResult.errorParam("不能为非会员充值,mallId:" + mallId, log);
                    return;
                }
                mallMember = mallMemberSrv.findOneById(mallMember.getId());
                MallMemberStatus status  =  mallMember.getStatus();

                if (MallMemberStatus.NOT_MEMBER == status) {
                    jsonResult.errorParam("不能为未认证会员充值,mallId:" + mallId, log);
                    return;
                } else if (MallMemberStatus.AUDITING == status) {
                    jsonResult.errorParam("会员开通审核中,不能充值,mallId:" + mallId, log);
                    return;
                } else if (MallMemberStatus.PROBATION_MEMBER == status) {//
                    jsonResult.errorParam("会员需要开通才能刚充值,mallId:" + mallId, log);
                    return;
                }


                MallMemberFundFlow mallMemberFundFlow = mallMemberRechargeSrv.rechargeSingle(mallMember,transactionType,rechargeAmount);

                String constantContent = SysMessageConstants.M2M_MALL_MERCHANT_RECHARGE_BATCH_SAVE.getContent();
                String content = MessageFormat.format(constantContent, DateUtils.getCurrentDate(DateFormatUtils.DATE_FORMAT2), rechargeAmount, "020-28187838");
                //广播消息
                SysMessageHelper.SINGLETON.pushFinanceMsg(SysMessageConstants.M2M_MALL_MERCHANT_RECHARGE_BATCH_SAVE, content,mallId,null);
            }

//

        };
        return doing.go(request, log);
    }
}
